import 'package:flutter/material.dart';

class ValueKeyProblemDemo extends StatefulWidget {
  @override
  _ValueKeyProblemDemoState createState() => _ValueKeyProblemDemoState();
}

class _ValueKeyProblemDemoState extends State<ValueKeyProblemDemo> {
  List<String> items = ['A', 'B', 'C'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('ValueKey 问题示例')),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: () {
              setState(() {
                items.insert(1, 'B'); // 插入重复的值
              });
            },
            child: Text('添加重复项'),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: items.length,
              itemBuilder: (context, index) {
                // 问题：使用重复的值作为 ValueKey
                return Card(
                  key: ValueKey(items[index]), // 当有重复值时会导致问题
                  child: ListTile(
                    title: Text('Item: ${items[index]}'),
                    trailing: IconButton(
                      icon: Icon(Icons.delete),
                      onPressed: () {
                        setState(() {
                          items.removeAt(index);
                        });
                      },
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(home: ValueKeyProblemDemo(), debugShowCheckedModeBanner: false));
}